package cj.web.cc.controllers;

import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.Page;
import cj.utils.sc.KDNiaoUtil;
import cj.web.cc.dao.MemberDAO;
import cj.web.constants.MemuEnum;
import cj.web.constants.SCOrderStatusEnum;
import cj.web.marriage.constants.SCShipperCodeEnum;
import cj.web.sc.dao.AppTokenDAO;
import cj.web.sc.dao.GoodsDAO;
import cj.web.sc.dao.OrderDAO;
import cj.web.uc.dao.LoginDAO;

@Path("shop")
public class ShopController extends BaseController{
	@Autowired
	private MemberDAO memberDAO;
	@Autowired
	private AppTokenDAO appTokenDao;
	@Autowired
	private OrderDAO orderDao;
	@Autowired
	private LoginDAO loginDao;
	@Autowired
	private GoodsDAO goodsDao;
	
	//----------收货地址--确认订单
	/**
	 * 收货地址选择
	 * @param model
	 * @param buyerId
	 * @param addressId
	 * @return
	 */
	@Get("addrchs")
	public String addressChoose(Model model, @Param("buyerId")int buyerId, @Param("addressId")String addressId){
		List<Map> Objs = memberDAO.getAddrByBuyerId(buyerId);
		model.add("Objs", Objs);
		model.add("buyerId", buyerId);
		model.add("addressId",addressId);
		return "/views/mall/addressSelect.vm";
	}
	
	/**
	 * 使用地址
	 * @param model
	 * @param buyerId
	 * @return
	 */
	@Get("addruse")
	public String addressUse(Model model, @Param("buyerId")int buyerId){
		model.add("buyerId",buyerId);
		return "/views/mall/addressUse.vm";
	}
	
	/**
	 * 编辑使用地址
	 * @param model
	 * @param addressId
	 * @return
	 */
	@Get("addrEditUse")
	public String addressEditUse(Model model, @Param("id")String addressId){
		List<Map> objs = memberDAO.getAddressById(addressId);
		if(objs != null && objs.size() > 0){
			model.add("Obj", objs.get(0));
		}
		return "/views/mall/addressEditUse.vm";
	}
	
	/**
	 * 修改地址
	 * @param id
	 * @param receiverName
	 * @param receiverPhone
	 * @param address_picker
	 * @param address
	 * @param isDefault
	 * @return
	 */
	@Post("addrUpdate")
	public String addressUpdate(@Param("id")String id, @Param("receiverName")String receiverName, @Param("receiverPhone")String receiverPhone, 
			@Param("address_picker")String address_picker, @Param("address")String address, @Param("isDefault")int isDefault){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String[] addrs = address_picker.split(" ");
		if(addrs != null && addrs.length > 0){
			String province = "";
			String city = "";
			String area = "";
			if( addrs.length == 2 ){
				province = addrs[0];
				city = addrs[1];
			}
			else if( addrs.length == 3 ){
				province = addrs[0];
				city = addrs[1];
				area = addrs[2];
			}
			List<Map> objs = memberDAO.getAddressById(id);
			if(objs != null && objs.size() > 0){
				int defaultFlag = Integer.parseInt(objs.get(0).get("isDefault").toString());
				if( defaultFlag == 0 && isDefault == 1){
					int buyerId = Integer.parseInt(objs.get(0).get("buyerId").toString());
					memberDAO.notDefaultByBuyerId(buyerId);
				}
				memberDAO.updateAddress(id, receiverName, receiverPhone, province, city, area, address, isDefault);
			}
			else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			}
			
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	//----------收货地址--我的个人中心
	/**
	 * 收货地址列表
	 * @param model
	 * @param request
	 * @return
	 */
	@Get("addrlst")
	public String addressList(Model model, HttpServletRequest request){
		int buyerId = getBuyerId(request);
		List<Map> Objs = memberDAO.getAddrByBuyerId(buyerId);
		model.add("Objs", Objs);
		model.add("buyerId", buyerId);
		return "/views/mall/addressList.vm";
	}
	
	/**
	 * 收货地址列表Pc
	 * @param model
	 * @param request
	 * @return
	 */
	@Get("addrPclst")
	public String addressPcList(Model model, HttpServletRequest request){
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			List<Map> addresslis = memberDAO.getAddrByBuyerId(Integer.parseInt(memberId));
			
			model.add("addresslis", addresslis);
			model.add("memberId", memberId);
			model.add("phone", phone);
			model.add("currentMemu", MemuEnum.shdz);
			model.add("currentTopMemu", MemuEnum.memugrzx);
		}
		return "/views/mallPC/address.vm";
	}
	
	/**
	 * 收货地址添加
	 * @param model
	 * @param buyerId
	 * @return
	 */
	@Get("addradd")
	public String addressAdd(Model model, @Param("buyerId")int buyerId){
		model.add("buyerId",buyerId);
		return "/views/mall/addressAdd.vm";
	}
	
	/**
	 * 添加地址
	 * @param buyerId
	 * @param receiverName
	 * @param receiverPhone
	 * @param address_picker
	 * @param address
	 * @param isDefault
	 * @return
	 */
	@Post("addrCrt")
	public String addressCreate(@Param("buyerId")int buyerId, @Param("receiverName")String receiverName, @Param("receiverPhone")String receiverPhone, 
			@Param("address_picker")String address_picker, @Param("address")String address, @Param("isDefault")int isDefault){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String[] addrs = address_picker.split(" ");
		if(addrs != null && addrs.length > 0){
			String province = "";
			String city = "";
			String area = "";
			if( addrs.length == 2 ){
				province = addrs[0];
				city = addrs[1];
			}
			else if( addrs.length == 3 ){
				province = addrs[0];
				city = addrs[1];
				area = addrs[2];
			}

			if(isDefault == 1){
				memberDAO.notDefaultByBuyerId(buyerId);
			}
			
			String phone = memberDAO.getPhoneById(buyerId);
			int id = memberDAO.createAddress(buyerId, receiverName, receiverPhone, province, city, area, address, isDefault, phone);
			jo.put("id", id);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 编辑地址
	 * @param model
	 * @param addressId
	 * @return
	 */
	@Get("addrEdit")
	public String addressEdit(Model model, @Param("id")String addressId){
		List<Map> objs = memberDAO.getAddressById(addressId);
		if(objs != null && objs.size() > 0){
			model.add("Obj", objs.get(0));
		}
		return "/views/mall/addressEdit.vm";
	}
	
	/**
	 * 删除地址
	 * @param addressId
	 * @return
	 */
	@Post("addrDel")
	public String addressDelete(@Param("id")int addressId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		memberDAO.delAddrById(addressId);
		
		return "@" + jo.toString();
	}
	
	/**
	 * 设置为默认
	 * @param addressId
	 * @return
	 */
	@Post("setDefault")
	public String setDefaultAddress(@Param("id")String addressId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> objs = memberDAO.getAddressById(addressId);
		if(objs != null && objs.size() > 0){
			int buyerId = Integer.parseInt(objs.get(0).get("buyerId").toString());
			memberDAO.notDefaultByBuyerId(buyerId);
			memberDAO.setDefalut(addressId);
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	//-----------订单
	
	/**
	 * pc版商城我的订单
	 * @param model
	 * @return
	 */
	@Get("pcOr")
	public String getOrdersForPc(Model model, HttpServletRequest request) {
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
		}
		model.add("currentMemu", MemuEnum.wddd);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		model.add("Status", EnumSet.allOf(SCOrderStatusEnum.class));
		model.add("logisticsPrice", LOGISTICS_FEE);
		return "/views/mallPC/orderList.vm";
	}
	
	/**
	 * pc版商城我的订单分页
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 */
	@Post("pcOrlis")
	public String getOrderslis(@Param("start") int start,@Param("length") int length, HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		int buyerId = getBuyerId(request);
		List<Map> repsList = orderDao.getOrders(buyerId, start*length, length);
		if(repsList != null && repsList.size() > 0){
			for(Map obj : repsList){
				int orderId = Integer.parseInt(obj.get("id").toString());
				List<Map> items = orderDao.getItemsByOrderId(orderId);
				obj.put("Items", items);
				obj.put("ItemSize", items.size());
				obj.put("statusName", SCOrderStatusEnum.getName(Integer.parseInt(obj.get("status").toString())));
			}
		}
		
		int totalCount = orderDao.getOrderSize(buyerId);
		
		//分页计算
		Page p= new Page<Map>(0, length, repsList, totalCount);
		
		jo.put("list", repsList);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		return "@"+jo.toString();
	}
	
	/**
	 * 详情
	 * @param model
	 * @param orderId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("orderPcDetail")
	public String orderPcDetail(Model model, @Param("orderId")int orderId, HttpServletRequest request) throws Exception{
		List<Map> objs = orderDao.getOrderById(orderId);
		if(objs != null && objs.size() > 0){
			List<Map> items = orderDao.getItemsByOrderId(orderId);
			objs.get(0).put("Items", items);
			objs.get(0).put("ItemSize", items.size());
			//下单时间
			String strDate = objs.get(0).get("createAt").toString();
			String createAt = DateUtils.formatDateStr(strDate, DateUtils.DATE_FULL_STR);
			objs.get(0).put("createAt", createAt);
			//付款时间
			if(objs.get(0).get("payAt")!=null){
				String payAt = objs.get(0).get("payAt").toString();
				payAt = DateUtils.formatDateStr(payAt, DateUtils.DATE_FULL_STR);
				objs.get(0).put("payAt", payAt);
			}else{
				objs.get(0).put("payAt", null);
			}
			objs.get(0).put("statusName", SCOrderStatusEnum.getName(Integer.parseInt(objs.get(0).get("status").toString())));
			model.add("obj", objs.get(0));
		}
		model.add("logisticsPrice", LOGISTICS_FEE);
		model.add("currentMemu", MemuEnum.wddd);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/mallPC/orderDetail.vm";
	}
	
	/**
	 * 物流追踪
	 * @param model
	 * @param orderId
	 * @return
	 */
	@Get("showPcLogistics")
	public String showPcLogistics(Model model, HttpServletRequest request, @Param("orderId")int orderId)
	{
		if(isLogin(request)){
			String phone = getCookieValueByName(request, "phone");
			String memberId = getCookieValueByName(request, "memberId");
			model.add("memberId", memberId);
			model.add("phone", phone);
			
			List<Map> objs = orderDao.getOrderById(orderId);
			model.add("obj", objs.get(0));
		}
		model.add("currentMemu", MemuEnum.wddd);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/mallPC/logistics.vm";
	}
	
	/**
	 * 微信商城我的订单
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("orders")
	public String orders(Model model, HttpServletRequest request) throws Exception{
		model.add("logisticsPrice", LOGISTICS_FEE);
		int buyerId = getBuyerId(request);
		List<Map> Objs = orderDao.getOrders(buyerId);
		if(Objs != null && Objs.size() > 0){
			for(Map obj : Objs){
				int orderId = Integer.parseInt(obj.get("id").toString());
				List<Map> items = orderDao.getItemsByOrderId(orderId);
				obj.put("Items", items);
			}
		}
		else{
			model.add("warning", "暂无订单");
			return "/views/mall/orderNothing.vm";
		}
		
		model.add("Objs", Objs);
		model.add("Status", EnumSet.allOf(SCOrderStatusEnum.class));
		
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		return "/views/mall/orders.vm";
	}
	
	/**
	 * 详情
	 * @param model
	 * @param orderId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("order")
	public String orderItem(Model model, @Param("id")int orderId, HttpServletRequest request) throws Exception{
		model.add("logisticsPrice", LOGISTICS_FEE);
		List<Map> objs = orderDao.getOrderById(orderId);
		if(objs != null && objs.size() > 0){
			List<Map> items = orderDao.getItemsByOrderId(orderId);
			objs.get(0).put("Items", items);
			String strDate = objs.get(0).get("createAt").toString();
			String createAt = DateUtils.formatDateStr(strDate, DateUtils.DATE_FULL_STR);
			objs.get(0).put("createAt", createAt);
			model.add("Obj", objs.get(0));
		}
		
		model.add("Status", EnumSet.allOf(SCOrderStatusEnum.class));
		
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		return "/views/mall/order.vm";
	}
	
	/**
	 * 取消订单商城
	 * @param id
	 * @return
	 */
	@Post("orderCancel")
	public String orderCancel(@Param("id")int id){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		List<Map> objs = orderDao.getOrderById(id);
		if(objs != null && objs.size() > 0){
			if(SCOrderStatusEnum.prepay.getValue()==Integer.parseInt(objs.get(0).get("status").toString())){
				orderDao.cancelOrderById(id);
			}else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_3);
			}
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 物流追踪
	 * @param model
	 * @param orderId
	 * @return
	 */
	@Get("showLogistics")
	public String showLogistics(Model model, @Param("orderId")int orderId)
	{
		List<Map> orderObj = orderDao.getOrderById(orderId);
		model.add("obj", orderObj.get(0));
		
		if(orderObj!=null && orderObj.size()>0){
			model.add("id", orderObj.get(0).get("id").toString());
			//shipCode
			String expressCom = orderObj.get(0).get("expressCom").toString();
			String expressBill = orderObj.get(0).get("expressBill").toString();
			
			KDNiaoUtil api = new KDNiaoUtil();
			try {
				String result = api.getOrderTracesByJson(expressCom, expressBill);
				
				JSONObject jo = new JSONObject().fromObject(result);
				//物流路线
				JSONArray jslis = jo.getJSONArray("Traces");
				List<Map> list = JSONArray.toList(jslis, Map.class);// 过时方法
				Collections.reverse(list);
				
				model.add("list",list);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			model.add("expressName",SCShipperCodeEnum.getName(expressCom));
			model.add("expressCom",expressCom);
			model.add("expressBill", orderObj.get(0).get("expressBill").toString());
		}else{
			model.add("id", "");
			model.add("expressCom", "");
			model.add("expressBill", "");
			model.add("list","");
		}
		
		return "/views/mall/logistics.vm";
	}
	
	/**
	 * 个人中心支付验证
	 * @param orderId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Post("alipay")
	public String alipay(@Param("orderId")int orderId, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> orderObj = orderDao.getOrderById(orderId);
		
		if(orderObj != null && orderObj.size() > 0){
			Map order = orderObj.get(0);
			
			int status = Integer.parseInt(order.get("status").toString());
			if( status != SCOrderStatusEnum.prepay.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2); //该订单已付款或失效
				return "@" + jo.toString();
			}
			
			//验证商品 及 库存
			List<Map> orderItems = orderDao.getItemsByOrderId(orderId);
			for(Map orderItem : orderItems){
				String goodsName = orderItem.get("goodsItemName").toString();
				int goodsItemId = Integer.parseInt(orderItem.get("goodsItemId").toString());
				int count = Integer.parseInt(orderItem.get("count").toString());
				
				List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
				if(goodsItem != null && goodsItem.size() > 0){
					Map goods = goodsItem.get(0);
					int inventory = Integer.parseInt(goods.get("inventory").toString());
					if( inventory < count ){
						jo.put("info", goodsName + "库存不足");
						jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
						jo.put("returnCode", Constants.returnObj.returnCode.code_3);
						return "@" + jo.toString();
					}
					
					int goodsId = Integer.parseInt(goods.get("goodsId").toString());
					List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
					if(goodsObj == null){
						jo.put("info", goodsName + "已下架");
						jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
						jo.put("returnCode", Constants.returnObj.returnCode.code_4);
						return "@" + jo.toString();
					}
				}
				else{
					jo.put("info", goodsName + "已下架");
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnCode", Constants.returnObj.returnCode.code_4);
					return "@" + jo.toString();
				}
			}
			
	        return "@" + jo.toString();
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1); //该订单已失效
			return "@" + jo.toString();
		}
		
	}
	
	/**
	 * 从Cookie中获取购买人ID
	 * @param request
	 * @return
	 */
	private int getBuyerId(HttpServletRequest request){
		int memberId = Integer.parseInt(getCookieValueByName(request, "memberId"));
		return memberId;
    }
}